import cv2
import numpy as np
import os


def expand_background(input_path, output_path, scale=2, bg_color=(255, 255, 255)):
    """
    改进后的背景扩展函数
    :param input_path: 输入图片路径
    :param output_path: 输出图片路径
    :param scale: 缩放倍数（建议1.5-3）
    :param bg_color: 背景色(BGR格式)
    :return: 处理后的图像
    """

    if not os.access(input_path, os.R_OK):
        print(f"错误：没有读取权限！请检查文件权限。")
        exit()

    if not os.path.exists(input_path):
        print(f"错误：文件不存在！请检查路径：{input_path}")
        exit()

    # 1. 读取并验证输入
    img = cv2.imread(input_path)
    if img is None:
        raise FileNotFoundError(f"图片路径无效: {input_path}")

    h, w = img.shape[:2]
    if h == 0 or w == 0:
        raise ValueError("输入图片尺寸异常")

    # 2. 改进的边缘检测
    # - 转换为Lab颜色空间提高对比度
    lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
    l, a, b = lab[:, :, 0], lab[:, :, 1], lab[:, :, 2]

    # - 使用自适应阈值处理不同光照
    edges = cv2.Canny(cv2.resize(img, (w // 2, h // 2)), 50, 150)
    edges = cv2.resize(edges, (w, h), interpolation=cv2.INTER_CUBIC)

    # 3. 智能画布扩展
    new_w = int(w * scale)
    new_h = int(h * scale)
    canvas = np.zeros((new_h, new_w, 3), dtype=np.uint8)

    # 4. 高质量图像缩放
    resized_img = cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_LANCZOS4)

    # 5. 多通道掩码处理
    mask = np.stack([edges] * 3, axis=-1).astype(np.bool_)

    # 6. 动态背景填充
    background = np.where(mask, resized_img, bg_color)

    # 7. 后处理增强
    background = cv2.GaussianBlur(background, (3, 3), 0)
    return cv2.imwrite(output_path, background), background


# 使用示例
success, _ = expand_background(
    input_path="D:/Desk/exif需求/IMG_6501.jpg",
    output_path="D:/Desk/exif需求/target.jpg",
    scale=2,
    bg_color=(0, 128, 255)  # 蓝色背景(BGR)
)

if success:
    print("背景扩展成功！")
else:
    print("保存失败，请检查路径权限")